package com.sqbang.dbcompare.advice;

import com.sqbang.dbcompare.pojo.model.BizException;
import com.sqbang.dbcompare.pojo.model.R;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 异常处理类
 *
 * @author suqiongbang
 * @date 2021/12/14 11:12
 */
@RestControllerAdvice
public class ControllerExceptionHandler {

    /**
     * Biz exception handler
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public R businessErrorHandler(BizException e) {
        int code = StringUtils.isEmpty(e.getCode()) ? HttpStatus.INTERNAL_SERVER_ERROR.value() : e.getCode();
        String msg = StringUtils.isEmpty(e.getMsg()) ?HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase() : e.getMsg();
        R<String> response = new R<>();
        response.setCode(code);
        response.setMsg(msg);
        return response;
    }

    /**
     * 用于拦截get请求参数缺失
     *
     * @param e MissingServletRequestParameterException
     * @return
     */
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    @ResponseBody
    public R requestErrorHandler(MissingServletRequestParameterException e) {
        return R.error(HttpStatus.BAD_REQUEST);
    }


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public R systemErrorHandler(Exception e) {
        e.printStackTrace();
        return R.error(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * validation 异常处理， 返回检测提示
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public R<?> handleException(final MethodArgumentNotValidException e) {
        e.printStackTrace();
        return R.error(HttpStatus.BAD_REQUEST);
    }

}
